<?php

namespace Home\Controller; //当前命名空间跟文件目录一样
use Common\Common\CommonController; //引用Common目录下的Common下的CommonController
class CarController extends CommonController
{

	//展示用户购物车数据
	public function show()
	{
		//调用公共控制器中的检查用户身份
		$this->checkUser();
		$user_name = session('u_name'); //获取当前登录的用户名
		//实例化User模型对象，使用relation方法进行关联操作,我们只需要关联Car表和User表，所以我们在relation传入参数Car，就能实现只关联car和user，而不关联order
		$car_info = D('User')->relation('Car')->where(array('u_name' => $user_name))->select();  //只查询当前用户名相关购物车信息
		//使用assign()方法分配数据
		$this->assign('car_info', $car_info);
		//显示视图
		$this->display();
	}
	//添加商品到购物车
	public function add()
	{
		//调用公共控制器中的检查用户身份
		$this->checkUser();
		$goods_id = intval(I('get.gi')); //获取get传递过来的商品编号
		$user_name = session('u_name'); //获取当前登录的用户名
		//判断商品是否已存在登录用户的购物车中
		$modelUser = D('User');
		$carInfo = $modelUser->relation('Car')->where(array('u_name' => $user_name))->find()['Car']; //查询登录用户购物车信息
		foreach ($carInfo as $value) {
			if ($goods_id == $value['goods_id'])  //循环判断购物车是否存在同名商品
			{
				$this->error("添加失败！购物车已有相同的商品", U('?m=home&c=goods&a=item&gi=' . $goods_id));
				die();
			}
		}
		//实例化Car模型对象
		$modelCar = M('Car');
		//实例化Goods模型对象
		$modelGoods = M('Goods');
		$goodsInfo = $modelGoods->where(array('goods_id' => $goods_id))->find(); //获取添加的商品信息
		$user_id = $modelUser->relation(FALSE)->where(array('u_name' => $user_name))->select()[0]['user_id']; //获取当前用户id
		$where = array(
			'category_id' => $goodsInfo['category_id'],
			'goods_name' => $goodsInfo['goods_name'],
			'goods_price' => $goodsInfo['goods_price'],
			'pic_url' => $goodsInfo['pic_url'],
			'goods_id' => $goodsInfo['goods_id'],
			'user_id' => $user_id,
		);
		$modelCar->add($where);  //添加到购物车	  
		$this->success("添加成功！记得到购物车查看哦！", U('?m=home&c=goods&a=item&gi=' . $goods_id));
	}

	//将商品从购物车移除
	public function delete()
	{
		//调用公共控制器中的检查用户身份
		$this->checkUser();
		$car_id = I('get.cai');
		$model = M('Car');
		if (!empty($model->where(array('car_id' => $car_id))->delete())) {
			$this->success("商品移出购物车成功！", U('?m=home&c=car&a=show'));
			die;
		}
		$this->error("非法错误，商品移出购物车失败！", U('?m=home&c=car&a=show'));
	}
}
